import javax.swing.*;
import javax.swing.table.DefaultTableCellRenderer;
import java.awt.*;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.util.ArrayList;

public class PoneBookJFrame extends JFrame {
    private JList<String> jList;
    private JTextField nameText;
    private JTable table;
    private MyTableModel [] model = new MyTableModel[100];
    //多种friends实例的关系分类
    private ArrayList<Friend>friends_for_search;
    private ArrayList<Friend> [] friends = new ArrayList[100];

    private PoneBookJFrame(){
        super("电话簿");
        this.setSize(600,300);
        this.setLocationRelativeTo(null);
        this.setDefaultCloseOperation(EXIT_ON_CLOSE);

        JPanel rightPanel = new JPanel(new BorderLayout());
        JPanel bottomPanel = new JPanel(new GridLayout(2,1));
        DefaultListModel <String>dlm = new DefaultListModel<>();
        dlm.addElement("全部");
        dlm.addElement("张");
        dlm.addElement("王");
        dlm.addElement("李");
        dlm.addElement("郑");
        dlm.addElement("朱");

        jList = new JList<>();
        jList.setModel(dlm);
        JScrollPane leftPanel = new JScrollPane(jList);
        jList.setFont(new Font("等线", Font.PLAIN, 18));



        init();//初始化表格
        table = new JTable(model[0]);
        JScrollPane topPanel = new JScrollPane(table);
        table.setRowHeight(25);
        DefaultTableCellRenderer r = new DefaultTableCellRenderer();
        r.setHorizontalAlignment(JLabel.CENTER);
        table.setDefaultRenderer(Object.class, r);//设置居中方式
        table.setFont(new Font("等线", Font.PLAIN, 18));

        JLabel name = new JLabel("姓名");
        name.setHorizontalAlignment(JTextField.CENTER);
        nameText = new JTextField("");
        nameText.setHorizontalAlignment(JTextField.CENTER);
        JLabel phone = new JLabel("电话号码");
        phone.setHorizontalAlignment(JTextField.CENTER);
        JTextField phoneText = new JTextField("");
        phoneText.setHorizontalAlignment(JTextField.CENTER);
        JButton buttonAdd = new JButton("添加");
        JButton buttonDelete = new JButton("删除");
        JButton buttonUpdate = new JButton("修改");
        JButton buttonSearch = new JButton("按电话号码查找");

        bottomPanel.add(name);
        bottomPanel.add(nameText);
        bottomPanel.add(phone);
        bottomPanel.add(phoneText);
        bottomPanel.add(buttonAdd);
        bottomPanel.add(buttonDelete);
        bottomPanel.add(buttonUpdate);
        bottomPanel.add(buttonSearch);

        //垂直隔条
        JSplitPane split2 = new JSplitPane(JSplitPane.VERTICAL_SPLIT, topPanel,bottomPanel);
        //水平隔条
        JSplitPane split1 = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT,leftPanel,rightPanel);
        split1.setDividerLocation(50);
        split2.setDividerLocation(160);
        this.getContentPane().add(split1,BorderLayout.CENTER);
        split1.setRightComponent(split2);


        /*
         * 列表框选择监听器
         * */
        jList.addListSelectionListener(e -> {
            if(e.getValueIsAdjusting()){
                int index = jList.getLeadSelectionIndex();
                table.setModel(model[index]);
            }
        });


        /*
         * 查询朋友的监听器
         * */
        buttonSearch.addActionListener(e -> {
            if(phoneText.getText().length()==11){
                friends_for_search = new ArrayList<>();
                String nameValue = "";
                for (Friend friend : friends[0]) {
                    if (friend.getPhoneNumber().equals(phoneText.getText())){
                        nameValue = friend.getName();
                    }
                }
                if(nameValue.length()>0){
                    Friend friend = new Friend(nameValue,phoneText.getText());
                    friends_for_search.add(friend);
                    table.setModel(updateModel(friends_for_search));
                }else{
                    JOptionPane.showMessageDialog(null,"未找到联系人，请核实信息");
                }
            }
            else
                JOptionPane.showMessageDialog(null,"手机号格式不正确");


        });
        /*
         * 删除朋友的监听器
         * */
        buttonDelete.addActionListener(e -> {
            if(table.getSelectedRows().length>0){
                String str = table.getValueAt(table.getSelectedRow(),0).toString();
                model[0] = afterRemove(friends[0],str);
                table.setModel(model[0]);
                ListModel<String> m=jList.getModel();
                String [] firstName = new String[m.getSize()];
                for (int i = 0; i < m.getSize(); i++) {
                    firstName[i] = m.getElementAt(i);
                }
                for (int i = 0; i <firstName.length; i++) {
                    if(firstName[i].equals(str.substring(0,1))){
                        model[i]=afterRemove(friends[i],str);
                        break;//找到就退出循环，加快速度
                    }
                }
            }
            else
                JOptionPane.showMessageDialog(null,"未选中任何要删除的联系人！");

        });
        /*
         * 添加朋友的监听器
         * */
        buttonAdd.addActionListener(e -> {
            if(nameText.getText().length()>0&&phoneText.getText().length()==11){
                Friend friend = new Friend(nameText.getText(),phoneText.getText());
                friends[0].add(friend);
                model[0] = updateModel(friends[0]);
                table.setModel(model[0]);
                ListModel<String> m=jList.getModel();
                String [] firstName = new String[m.getSize()];
                for (int i = 0; i < m.getSize(); i++) {
                    firstName[i] = m.getElementAt(i);
                }
                for (int i = 0; i <firstName.length; i++) {
                    if(firstName[i].equals(nameText.getText().substring(0,1))) {
                        friends[i].add(friend);
                        model[i] = updateModel(friends[i]);
                        break;//如果相等则退出循环
                    }
                    /*
                     * 如果没有找到，说明标签里没有，标签里添加一个
                     * */
                    if(i==firstName.length-1){

                        dlm.addElement(nameText.getText().substring(0,1));
                        jList.setModel(dlm);
                        System.out.println(m.getSize());
                        friends[m.getSize()-1].add(new Friend(nameText.getText(),phoneText.getText()));
                        model[m.getSize()-1] = updateModel(friends[m.getSize()-1]);
                    }
                }
            }
            else
                JOptionPane.showMessageDialog(null,"姓名和手机号码格式不规范！","警告",JOptionPane.ERROR_MESSAGE);

        });
        /*
         * 修改朋友的监听器
         * */
        buttonUpdate.addActionListener(e -> {
            int count = 0;
            ArrayList<Integer>modelIndex = null;
            ListModel<String> m=jList.getModel();
            String [] firstName = new String[m.getSize()];
            for (int i = 0; i < m.getSize(); i++) {
                firstName[i] = m.getElementAt(i);
                if(model[i].getEditedIndex().size()>0) {
                    count = model[i].getEditedIndex().size();
                    modelIndex = model[i].getEditedIndex();
                }
            }
            if(count>0&&modelIndex!=null){
                for (int i = 0; i <count; i++) {
                    int index = modelIndex.get(i);
                    String nameValue =table.getValueAt(index,0).toString();
                    String phoneValue = table.getValueAt(index,1).toString();
                    model[0] = afterUpdate(friends[0],nameValue,phoneValue);
                    for (int j = 0; j <firstName.length; j++) {
                        if(firstName[j].equals(nameValue.substring(0,1))){
                            model[j]=afterUpdate(friends[j],nameValue,phoneValue);
                            break;
                        }
                    }
                }
            }
        });

        this.setVisible(true);
    }

    /*
     * 更新表格之后设置friend的姓名，手机号
     * 返回一个表格模型
     * */
    private MyTableModel afterUpdate(ArrayList<Friend>friends,String nameValue,String phoneValue){
        for (Friend friend : friends) {
            if (friend.getName().equals(nameValue)) {
                friend.setName(nameValue);
                friend.setPhoneNumber(phoneValue);
            }
        }
        return updateModel(friends);
    }

    /*
     * 删除表格中选中行对应的对象
     * 并且返回一个新的表格模型
     * */
    private MyTableModel afterRemove(ArrayList<Friend>friends,String str){
        for (int i = 0; i <friends.size(); i++) {
            if(friends.get(i).getName().equals(str))
                friends.remove(i);
        }
        return updateModel(friends);
    }
    /*
     * 更新表格，复用
     * */
    private MyTableModel updateModel(ArrayList<Friend> friends){
        MyTableModel model = new MyTableModel();
        model.addColumn("姓名");
        model.addColumn("电话号码");
        for (Friend friend : friends)
            model.addRow(new Object[]{friend.getName(), friend.getPhoneNumber()});
        return model;
    }

    public static void writeObjectToFile(Object obj)
    {
        File file =new File("phone_book.dat");
        FileOutputStream out;
        try {
            out = new FileOutputStream(file);
            ObjectOutputStream objOut=new ObjectOutputStream(out);
            objOut.writeObject(obj);
            objOut.flush();
            objOut.close();
            System.out.println("write object success!");
        } catch (IOException e) {
            System.out.println("write object failed");
            e.printStackTrace();
        }
    }
    /*
     * 初始化表格
     * */
    private void init(){

        for (int i = 0; i <100; i++) {
            friends[i] = new ArrayList<>();
        }

        friends[0].add(new Friend("张东璨","15950803241"));
        friends[0].add(new Friend("王伟","15256482367"));
        friends[0].add(new Friend("李晓明","15951737201"));
        friends[0].add(new Friend("郑浩","17857946305"));
        friends[0].add(new Friend("朱红","17805188216"));

        friends[1].add(new Friend("张东璨","15950803241"));
        friends[2].add(new Friend("王伟","15256482367"));
        friends[3].add(new Friend("李晓明","15951737201"));
        friends[4].add(new Friend("郑浩","17857946305"));
        friends[5].add(new Friend("朱红","17805188216"));

        for (int i = 0; i <100; i++) {
            model[i] = new MyTableModel();
        }
        MyTableModel model_for_search = new MyTableModel();

        for (int i = 0; i <100; i++) {
            model[i].addColumn("姓名");
            model[i].addColumn("电话号码");
        }
        model_for_search.addColumn("姓名");
        model_for_search.addColumn("电话号码");

        for (int i = 0; i <6; i++) {
            for (Friend friend : friends[i])
                model[i].addRow(new Object[]{friend.getName(), friend.getPhoneNumber()});
        }
    }


    public static void main(String[] args) {
        new PoneBookJFrame();

    }
}
